/*
 * Copyright 2019-present HiveMQ GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hivemq.extensions.rbac.redis.utils;

import com.codahale.metrics.MetricRegistry;
import com.hivemq.extension.sdk.api.annotations.ThreadSafe;
import com.hivemq.extension.sdk.api.auth.parameter.TopicPermission;
import com.hivemq.extension.sdk.api.services.builder.Builders;
import com.hivemq.extensions.rbac.redis.configuration.entities.ExtensionRedisConfig;
import com.hivemq.extensions.rbac.redis.configuration.entities.Permission;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Objects;

/**
 * Redis-Key 证书验证器
 */
@ThreadSafe
public class RedisKeyOnecCredentialsValidator {
    private static final @NotNull Logger log = LoggerFactory.getLogger(RedisKeyOnecCredentialsValidator.class);

    private final @NotNull ExtensionRedisConfig extensionRedisConfig;
    private static JedisPool jedisPool = null;
    private Jedis jedis;

    public RedisKeyOnecCredentialsValidator(
            final @NotNull ExtensionRedisConfig extensionRedisConfig,
            final @NotNull MetricRegistry metricRegistry) {
        this.extensionRedisConfig = extensionRedisConfig;

    }

    public void init() {

        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(extensionRedisConfig.getRedisMaxTotal());
            config.setMaxIdle(extensionRedisConfig.getRedisMaxIdle());
            config.setMaxWaitMillis(extensionRedisConfig.getRedisMaxWaitNillis());
            config.setTestOnBorrow(extensionRedisConfig.isRedisTestOnBorrow());
            jedisPool = new JedisPool(config, extensionRedisConfig.getRedisHost(),
                    extensionRedisConfig.getRedisPort(),
                    extensionRedisConfig.getRedisTimeOut(), extensionRedisConfig.getRedisPassword());

            jedis = getJedisPool();
        } catch (Exception e) {
            log.warn("Redis初始化失败{}", e.getMessage());
        }
    }

    public boolean exists(String key){
        jedis = getJedis();
        try{
            return jedis.exists(key);
        }catch (Exception e){
            next();
        }
        return jedis.exists(key);
    }

    public synchronized void next(){
        close();
        jedis = getJedis();
    }

    public Jedis getJedis() {
        if(jedis == null){
            jedis = getJedisPool();
        }
        return jedis;
    }


    public void close(){
        if(jedis != null){
            try{
                jedis.close();
            }catch (Exception e){
                log.error("jedis关闭失败");
                e.printStackTrace();
            }
            jedis = null;
        }
    }

    public synchronized Jedis getJedisPool() {
        return getJedisPool(extensionRedisConfig.getRedisDb());
    }

    /**
     * 获取连接池对象
     * @param index 指定数据库
     * @return
     */
    public synchronized static Jedis getJedisPool(int index) {
        try {
            if (jedisPool != null) {
                Jedis jedis = jedisPool.getResource();
                jedis.select(index);
                return jedis;
            } else {
                log.warn("获取Redis对象失败");
                return null;
            }
        } catch (Exception e) {
            log.warn("获取Redis对象失败:{}", e.getMessage());
            return null;
        }
    }

    //关闭redis连接池
    public static void closeJedisPool() {
        if (jedisPool != null) {
            log.info("关闭redis连接池");
            jedisPool.close();
        }
    }

    public @NotNull TopicPermission getPermission(String topic, TopicPermission.Qos qos, TopicPermission.MqttActivity activity){
        Permission permission = new Permission(topic);
        permission.setQos(qos);
        // 权限-订阅
        permission.setActivity(activity);
        return toTopicPermission(topic, permission);
    }

    private @NotNull TopicPermission toTopicPermission(
            final @NotNull String clientId, final @NotNull String userName, final @NotNull Permission permission) {
        return toTopicPermission(getTopicFilter(clientId, userName, permission), permission);
    }

    private @NotNull TopicPermission toTopicPermission(String topic, Permission permission) {
        return Builders.topicPermission()
                .topicFilter(topic)
                .activity(Objects.requireNonNull(permission.getActivity()))
                .type(TopicPermission.PermissionType.ALLOW)
                .retain(Objects.requireNonNull(permission.getRetain()))
                .qos(Objects.requireNonNull(permission.getQos()))
                .sharedSubscription(Objects.requireNonNull(permission.getSharedSubscription()))
                .sharedGroup(Objects.requireNonNull(permission.getSharedGroup()))
                .build();
    }

    private @NotNull String getTopicFilter(
            final @NotNull String clientId, final @NotNull String userName, final @NotNull Permission permission) {
        final String configTopic = permission.getTopic();
        return Substitution.substitute(Objects.requireNonNull(configTopic), clientId, userName);
    }
}
